//
//  LSWorkDayReportViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/24.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSWorkDayReportViewController.h"
#import "LSWorkDayReportTableViewCell.h"
#import "LSDatePickViewController.h"
#import "LSWorkDayReportDetailViewController.h"

#define CountPerPage 10

@interface LSWorkDayReportViewController () <UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate>
@property (nonatomic, strong) UITableView *workDayReportTableView;
@property (nonatomic, strong) UITextField *timeSelectBeginnerTF;
@property (nonatomic, strong) UITextField *timeSelectFinisherTF;
@property (nonatomic, assign) int tableViewPage;
@property (nonatomic, strong) NSMutableArray *dataArrayM;
@property (nonatomic, strong) NZKNoDataView *nodataView;
@property (nonatomic, strong) NZKNetworkErrorView *networkErrorView;
@end

static NSString *LSWorkDayReportTableViewCellID = @"LSWorkDayReportTableViewCellID";

@implementation LSWorkDayReportViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"工作日志";
//    [self setUpHeaderView];
    [self loadData];
    [self.view addSubview:self.workDayReportTableView];
    [self setUpAddButton];
    _workDayReportTableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadData)];
}

- (void)loadData {
    self.tableViewPage = 1;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"page":[NSString stringWithFormat:@"%d",self.tableViewPage]};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:WorkReportList param:param completionHandler:^(id responseObject, NSError *connectionError) {
        self.workDayReportTableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
        [self.workDayReportTableView.mj_header endRefreshing];
        if (!connectionError) {
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                [self.nodataView removeFromSuperview];
                [self.networkErrorView removeFromSuperview];
                self.dataArrayM = [[NSMutableArray alloc] initWithArray:dataArray];
                if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                    [self.workDayReportTableView.mj_footer endRefreshingWithNoMoreData];
                }
                [self.workDayReportTableView reloadData];
            } else {
                [self.dataArrayM removeAllObjects];
                [self.workDayReportTableView reloadData];
                [self.workDayReportTableView.mj_footer endRefreshingWithNoMoreData];
                [self.networkErrorView removeFromSuperview];
                [self.workDayReportTableView addSubview:self.nodataView];
            }
        } else {
            [self.nodataView removeFromSuperview];
            [self.workDayReportTableView addSubview:self.networkErrorView];
            self.networkErrorView.tipText = [NSString stringWithFormat:@"%@",connectionError.localizedDescription];
        }
    }];
}

- (void)loadMoreData {
    self.tableViewPage++;
    NSDictionary *param = @{@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token],@"rows":[NSString stringWithFormat:@"%d",CountPerPage],@"page":[NSString stringWithFormat:@"%d",self.tableViewPage]};
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:WorkReportList param:param completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            NSArray *dataArray = [responseObject objectForKey:@"data"];
            if (dataArray && dataArray.count > 0) {
                [self.dataArrayM addObjectsFromArray:dataArray];
                if (self.dataArrayM.count < self.tableViewPage*CountPerPage) {
                    [self.workDayReportTableView.mj_footer endRefreshingWithNoMoreData];
                } else {
                    [self.workDayReportTableView.mj_footer endRefreshing];
                }
                [self.workDayReportTableView reloadData];
            } else {
                self.tableViewPage--;
                [self.workDayReportTableView.mj_footer endRefreshingWithNoMoreData];
            }
        } else {
            self.tableViewPage--;
            [self.workDayReportTableView.mj_footer endRefreshing];
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

- (void)setUpAddButton {
    UIButton *addWorkDayReportButton = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-44)/2, (ScreenHeight-SafeAreaTopHeight)*0.8, 44, 44)];
    [addWorkDayReportButton setImage:[UIImage imageNamed:@"tianjia"] forState:UIControlStateNormal];
    [addWorkDayReportButton addTarget:self action:@selector(addWorkDayReportButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:addWorkDayReportButton];
}

#pragma mark - 添加新日志按钮点击事件
- (void)addWorkDayReportButtonClick {
    LSWorkDayReportDetailViewController *workDayReportDetailVC = [[LSWorkDayReportDetailViewController alloc] init];
    WS
    workDayReportDetailVC.refreshBlock = ^{
        [weakSelf loadData];
    };
    workDayReportDetailVC.title = @"添加日志";
    [self.navigationController pushViewController:workDayReportDetailVC animated:true];
}

- (void)setUpHeaderView {
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 40)];
    headerView.backgroundColor = UIColor.whiteColor;
    [self.view addSubview:headerView];
    UIView *headerViewBottomLineView = [[UIView alloc] initWithFrame:CGRectMake(0, 39.5, ScreenWidth, 0.5)];
    headerViewBottomLineView.backgroundColor = hexColor(CCCCCC);
    [headerView addSubview:headerViewBottomLineView];
    UILabel *timeSelectTipLabel = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2, 0, 38, 40) andText:@"时间:" andTextColor:hexColor(666666) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:12] andTextAlignment:NSTextAlignmentLeft];
    [headerView addSubview:timeSelectTipLabel];
    UITextField *timeSelectBeginnerTF = [[UITextField alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38, 10, 90, 20)];
    self.timeSelectBeginnerTF = timeSelectBeginnerTF;
    timeSelectBeginnerTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:11];
    timeSelectBeginnerTF.delegate = self;
    timeSelectBeginnerTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    timeSelectBeginnerTF.layer.borderWidth = 0.5;
    timeSelectBeginnerTF.backgroundColor = hexColor(EEEEEE);
    UIImageView *timeSelectBeginnerTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    timeSelectBeginnerTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
    timeSelectBeginnerTF.rightView = timeSelectBeginnerTFRightViewImageView;
    timeSelectBeginnerTF.rightViewMode = UITextFieldViewModeAlways;
    [headerView addSubview:timeSelectBeginnerTF];
    UILabel *zhiLabel = [[UILabel alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38+90, 0, 15, 40) andText:@"至" andTextColor:hexColor(666666) andFont:[UIFont fontWithName:@"SourceHanSansCN-Regular" size:12] andTextAlignment:NSTextAlignmentCenter];
    [headerView addSubview:zhiLabel];
    UITextField *timeSelectFinisherTF = [[UITextField alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38+90+15, 10, 90, 20)];
    self.timeSelectFinisherTF = timeSelectFinisherTF;
    timeSelectFinisherTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:11];
    timeSelectFinisherTF.delegate = self;
    timeSelectFinisherTF.layer.borderColor = hexColor(dbdbdb).CGColor;
    timeSelectFinisherTF.layer.borderWidth = 0.5;
    timeSelectFinisherTF.backgroundColor = hexColor(EEEEEE);
    UIImageView *timeSelectFinisherTFRightViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 20, 20)];
    timeSelectFinisherTFRightViewImageView.image = [UIImage imageNamed:@"xiala"];
    timeSelectFinisherTF.rightView = timeSelectFinisherTFRightViewImageView;
    timeSelectFinisherTF.rightViewMode = UITextFieldViewModeAlways;
    [headerView addSubview:timeSelectFinisherTF];
    UIButton *searchButton = [[UIButton alloc] initWithFrame:CGRectMake((ScreenWidth-310)/2+38+90+15+90+20, 10, 54, 20)];
    searchButton.backgroundColor = NAV_COLOR;
    [searchButton setTitle:@"搜索" forState:UIControlStateNormal];
    [searchButton setTitleColor:hexColor(f7f7f7) forState:UIControlStateNormal];
    searchButton.layer.cornerRadius = 3;
    searchButton.layer.masksToBounds = true;
    searchButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10];
    [searchButton addTarget:self action:@selector(searchButtonClick) forControlEvents:UIControlEventTouchUpInside];
    [headerView addSubview:searchButton];
}

#pragma mark - 搜索按钮点击事件
- (void)searchButtonClick {
    [MBProgressHUD showTipMessageInWindow:@"搜索"];
}

- (BOOL)textFieldShouldBeginEditing:(UITextField *)textField {
    if (textField == self.timeSelectBeginnerTF) {// 搜索开始时间段
        LSDatePickViewController *alertVC = [LSDatePickViewController alertControllerWithTitle:@"设置开始时间\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        alertVC.datePicker.datePickerMode = UIDatePickerModeDate;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 获取当前datePicker上面选择的时间
            NSDate *date = alertVC.datePicker.date;
            //    NSLog(@"-----%@", date);
            // 创建时间格式化工具
            NSDateFormatter *df = [[NSDateFormatter alloc] init];
            df.dateFormat = @"yyyy-MM-dd";
            NSString *str = [df stringFromDate:date];
            self.timeSelectBeginnerTF.text = [NSString stringWithFormat:@"    %@",str];
            self.timeSelectBeginnerTF.backgroundColor = UIColor.whiteColor;
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    } else {// 搜索结束时间段
        LSDatePickViewController *alertVC = [LSDatePickViewController alertControllerWithTitle:@"设置开始时间\n\n\n\n\n\n\n\n\n" message:nil preferredStyle:UIAlertControllerStyleActionSheet];
        alertVC.datePicker.datePickerMode = UIDatePickerModeDate;
        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:nil];
        UIAlertAction *okAction = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
            // 获取当前datePicker上面选择的时间
            NSDate *date = alertVC.datePicker.date;
            //    NSLog(@"-----%@", date);
            // 创建时间格式化工具
            NSDateFormatter *df = [[NSDateFormatter alloc] init];
            df.dateFormat = @"yyyy-MM-dd";
            NSString *str = [df stringFromDate:date];
            self.timeSelectFinisherTF.text = [NSString stringWithFormat:@"    %@",str];
            self.timeSelectFinisherTF.backgroundColor = UIColor.whiteColor;
        }];
        [alertVC addAction:cancelAction];
        [alertVC addAction:okAction];
        [self presentViewController:alertVC animated:YES completion:nil];
    }
    return false;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataArrayM.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    LSWorkDayReportTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:LSWorkDayReportTableViewCellID forIndexPath:indexPath];
    NSDictionary *dataDict = self.dataArrayM[indexPath.row];
    cell.mainTitleText = [ValidateUtils validateNull:dataDict[@"create_name"]];
    cell.timeText = [ValidateUtils validateNull:dataDict[@"create_date"]];
    cell.stateText = [ValidateUtils validateNull:dataDict[@"state"]];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:true];
    LSWorkDayReportDetailViewController *workDayReportDetailVC = [[LSWorkDayReportDetailViewController alloc] init];
    WS
    workDayReportDetailVC.refreshBlock = ^{
        [weakSelf loadData];
    };
    NSDictionary *dataDict = self.dataArrayM[indexPath.row];
    workDayReportDetailVC.title = @"日志详情";
    workDayReportDetailVC.createName = [ValidateUtils validateNull:dataDict[@"create_name"]];
    workDayReportDetailVC.createDate = [ValidateUtils validateNull:dataDict[@"create_date"]];
    workDayReportDetailVC.contentTV.text = [ValidateUtils validateNull:dataDict[@"context"]];
    workDayReportDetailVC.workDayReportId = [ValidateUtils validateNull:dataDict[@"id"]];
    [self.navigationController pushViewController:workDayReportDetailVC animated:true];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return LSWorkDayReportTableViewCellHeight;
}

- (NSArray<UITableViewRowAction*>*)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
    WS
    UITableViewRowAction *rowAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        // 点击删除时 do something
        NSDictionary *dataDict = weakSelf.dataArrayM[indexPath.row];
        if (![[ValidateUtils validateNull:dataDict[@"create_name"]] isEqualToString:@""] && ![[ValidateUtils validateNull:dataDict[@"create_name"]] isEqualToString:[ValidateUtils validateNull:[UserInfoModel sharedInstance].customerRealName]]) {
            [MBProgressHUD showTipMessageInWindow:@"删除失败\n您不能删除其他用户的日志"];
        } else {
            [weakSelf deleteWorkReportById:dataDict[@"id"]];
        }
    }];
    rowAction.backgroundColor = [UIColor redColor];
//    UITableViewRowAction *rowaction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        // 点击置顶时 do something
//
//    }];
//    rowaction.backgroundColor = NAV_COLOR;
    NSArray *arr = @[rowAction];//rowAction,
    return arr;
}

- (void)deleteWorkReportById:(NSString *)workReportId {
    WS
    UIAlertController *alertC = [UIAlertController alertControllerWithTitle:@"确定要删除吗？" message:nil preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
    UIAlertAction *confirmAction = [UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [weakSelf confirmDeleteWorkReportById:workReportId];
    }];
    [alertC addAction:cancelAction];
    [alertC addAction:confirmAction];
    [self presentViewController:alertC animated:true completion:nil];
}

- (void)confirmDeleteWorkReportById:(NSString *)workReportId {
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:WorkReportDelete param:@{@"id":workReportId,@"token":[ValidateUtils validateNull:[UserInfoModel sharedInstance].token]} completionHandler:^(id responseObject, NSError *connectionError) {
        if (!connectionError) {
            [self loadData];
        } else {
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

//// 修改编辑按钮文字
//- (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath {
//    return @"编辑";
//}

- (UITableView *)workDayReportTableView {
    if (!_workDayReportTableView) {
        _workDayReportTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight)];
        _workDayReportTableView.separatorInset = UIEdgeInsetsZero;
        _workDayReportTableView.delegate = self;
        _workDayReportTableView.dataSource = self;
        [_workDayReportTableView registerClass:[LSWorkDayReportTableViewCell class] forCellReuseIdentifier:LSWorkDayReportTableViewCellID];
        _workDayReportTableView.tableFooterView = [UIView new];
    }
    return _workDayReportTableView;
}

- (NSMutableArray<NSDictionary *> *)dataArrayM {
    if (!_dataArrayM) {
        _dataArrayM = [[NSMutableArray alloc] init];
    }
    return _dataArrayM;
}

- (NZKNoDataView *)nodataView {
    if (!_nodataView) {
        _nodataView = [[NZKNoDataView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight) withTip:@"暂无相关信息" andButtonText:nil];
    }
    return _nodataView;
}

- (NZKNetworkErrorView *)networkErrorView {
    if (!_networkErrorView) {
        WS
        _networkErrorView = [[NZKNetworkErrorView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-SafeAreaTopHeight) withRefreshBlock:^{
            [weakSelf loadData];
        }];
    }
    return _networkErrorView;
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
